/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
function ListNode (val, next) {
  this.val = (val === undefined ? 0 : val)
  this.next = (next === undefined ? null : next)
}
head = new ListNode(1)
a = new ListNode(2)
b = new ListNode(3)
c = new ListNode(4)
head.next = a, a.next = b, b.next = c
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var swapPairs = function (head) {
  if (head === null || head.next === null)
    return head
  const stack = []
  let p = head
  while (p) {
    stack.push(p)
    p = p.next
  }
  for (let i = 0; i < stack.length; i += 2) {
    if (stack[i] && stack[i + 1]) {
      temp = stack[i + 1]
      stack[i + 1] = stack[i]
      stack[i] = temp
    }
  }
  let i = 0
  while (i < stack.length - 1) {
    stack[i].next = stack[++i]
  }
  stack[stack.length - 1].next = null
  return stack[0]
}
// 用个数组存一下就行了，在链表上操作，汗流浃背了
swapPairs(head)